var multiparty = require("multiparty");
const COS = require("cos-nodejs-sdk-v5");
const { SecretId, SecretKey, Bucket, Region } = require("./cosConfig");

const cos = new COS({
  SecretId,
  SecretKey,
});
const path = "task-background-images/";

/**
 *
 * @param {where file save} path
 */

function getFormData(req, path) {
  return new Promise((resolve) => {
    var multipart = new multiparty.Form();
    multipart.uploadDir = path;
    resolve(multipart);
  });
}

function sendErrorInfo(res, prop) {
  let newProp = prop
    .split("")
    .map((item, index) => {
      return index === 0 ? item.toUpperCase() : item;
    })
    .join("");

  res.sned({
    code: 400,
    message: `no ${newProp} Available`,
  });
}

async function uploadImage(fileBuffer, type, name) {
  try {
    const data = await cos.putObject({
      Bucket,
      Region,
      Key: path + new Date().getTime() + name + `.${type}`,
      Body: fileBuffer,
      onProgress: (progressData) => {
        console.log(progressData);
      },
    });
    console.log(data, "==========49");
    const imageUrl = `https://${data.Location}`;
    return imageUrl;
  } catch (error) {
    console.log(error);
  }
}

module.exports = {
  getFormData,
  sendErrorInfo,
  uploadImage,
};
